#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：01_显示固定的页面.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/6/006 16:48 
"""

# import socket
# from multiprocessing import Process
#
#
# def handleClient(clientSocket):
#     '用一个新的进程，为一个客户端进行服务'
#     recvData = clientSocket.recv(2014)
#     requestHeaderLines = recvData.splitlines()
#     for line in requestHeaderLines:
#         print(line)
#
#     responseHeaderLines = "HTTP/1.1 200 OK\r\n"
#     responseHeaderLines += "\r\n"
#     responseBody = "hello world"
#
#     response = responseHeaderLines + responseBody
#     clientSocket.send(response.encode("utf-8"))
#     clientSocket.close()
#
#
# def main():
#     '作为程序的主控制入口'
#
#     serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#     serverSocket.bind(("", 7788))
#     serverSocket.listen(10)
#     while True:
#         clientSocket,clientAddr = serverSocket.accept()
#         clientP = Process(target = handleClient, args = (clientSocket,))
#         clientP.start()
#         clientSocket.close()
#
#
#
# if __name__ == '__main__':
#     main()
#
#




from multiprocessing import Process
from socket import *
import re

HTML_ROOT_DIR = "./html"

def ClientConetn(ClientSocket):
    recvData = ClientSocket.recv(1024)
    httpRequestMethodLine = recvData.splitlines()
    for line in httpRequestMethodLine:
        print(line)
    # print(httpRequestMethodLine[0])

    getFileName = re.match("[^/]+(/[^ ]*)", str(httpRequestMethodLine[0])).group(1)
    if getFileName == "/":
        FilePath = HTML_ROOT_DIR + "/index.html"
    else:
        FilePath = HTML_ROOT_DIR + "/"+getFileName

    try:
        fp = open(FilePath,"r",encoding="gbk")
    except IOError:
        response = "HTTP1.1 404 \r\n" \
             "\r\n" \
             "Not find"
    else:
        data = fp.read()
        response = "HTTP1.1 200 OK\r\n" \
                 "\r\n" + data
    finally:
        ClientSocket.send(response.encode("gbk"))
    ClientSocket.close()

if __name__ == '__main__':

    # 创建一个服务端的socket
    serSocket = socket(AF_INET, SOCK_STREAM)
    # 重复绑定端口
    serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serSocket.bind(("", 7798))
    serSocket.listen(10)
    while True:
        ClientSocket, ClientAddr = serSocket.accept()
        p = Process(target=ClientConetn, args=(ClientSocket,))
        p.start()
        ClientSocket.close()  # 无状态需要发送一个请求关闭一个
